﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Telerik.Web.UI;

public partial class Components_MasterData_CodeDetail : System.Web.UI.UserControl
{
    //*DatabaseHelper DB = new DatabaseHelper();
    DataTable dt = new DataTable();
    int ParentID = 26; //ID trong CSDL, bảng Function

    static int FormState = 0; //trạng thái form ban đầu

    //Các biến lưu khóa chính, khóa phụ
    string CMCode = "";
    string CDCode = "";

    string i_UserID;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                if (FormState == 1 && Session["CodeDetail"] == null)
                {
                    FormState = 0;
                }
                if (Session["CodeDetail"] != null)
                {
                    FormState = (int)Session["CodeDetail"];
                    Session["CodeDetail"] = null;
                }
                i_UserID = Session["UserName"].ToString();
                SetupForm();
                switch (FormState)
                {
                    case 0:
                        {
                            break;
                        }
                    default:
                        {
                            CMCode = Session["CodeDetail_CMCode"].ToString();
                            CDCode = Session["CodeDetail_CDCode"].ToString();
                            LoadDatatoForm();
                            break;
                        }
                }
            }

        }
        catch (Exception ex)
        {
            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;
        }
    }

    protected void SetupForm()
    {
        //Load dữ liệu cho các control khi vừa load form
        Utils.LoadDataToCombo(cboCMCode, "CodeDetail_cbo_CmCode", DbType.String, 0);
        cboCMCode.SelectedIndex = 0;

        Utils.LoadCodeDetail(cboStatus, "Status", 0);
        cboStatus.SelectedIndex = 0;

        //Load dữ liệu cho các control khi StateForm = 1,2
        txtCDCode.Text = "";
        txtNumberValue.Text = "0";
        txtOrdinal.Text = "1";
        SetEnable();
    }

    protected void ClearForm()
    {
        cboCMCode.SelectedIndex = 0;
        txtCDCode.Text = "";
        txtCDName.Text = "";
        txtStandardName.Text = "";
        txtNumberValue.Text = "";
        //dtpDateTimeValue.SelectedDate.Value = dr["DateTimeValue"].ToString();
        txtOrdinal.Text = "";
        txtRemark.Text = "";
        cboStatus.Text = "";
        FormState = 0;
    }

    protected void SetEnable()
    {
        switch (FormState)
        {
            case 0://Thêm mới
                {
                    btnDelete.Enabled = false;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    btnDelete.CssClass = "btn btn-sm btn-warning";

                    cboCMCode.Enabled = true;
                    txtCDCode.Enabled = true;
                    break;
                }
            case 1://Sửa/Xóa
                {
                    btnDelete.Enabled = true;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    cboCMCode.Enabled = false;
                    txtCDCode.Enabled = false;
                    break;
                }
            default://Chỉ xem
                {
                    btnDelete.Visible = false;
                    btnGotoList.Visible = false;
                    btnNew.Visible = false;
                    btnSave.Visible = false;
                    break;
                }
        }
    }

    protected void LoadDatatoForm()
    {
        try
        {
            DBDataContext dtx = LINQUtil.GetDBReadOnly();
            List<CodeDetail_LoadResult> listResult = dtx.CodeDetail_Load(CMCode, CDCode).ToList();
            if (listResult.Count == 1)
            {
                cboCMCode.Text = listResult[0].CMCode;
                cboCMCode.SelectedValue = listResult[0].CMCode;
                txtCDCode.Text = listResult[0].CDCode;
                txtCDName.Text = listResult[0].CDName;
                txtStandardName.Text = listResult[0].StandardName;
                txtNumberValue.Text = listResult[0].NumberValue.ToString();
                txtOrdinal.Text = listResult[0].Ordinal.ToString();
                txtRemark.Text = listResult[0].Remark;
                cboStatus.SelectedValue = listResult[0].Status.ToString();
            }
        }
        catch (Exception ex)
        {
            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;
        }
    }

    bool IsExistCodeDetail(string cmcode, string cdcode)
    {
        DBDataContext dtx = LINQUtil.GetDBReadOnly();
        List<CodeDetail_CheckExistResult> ltResult = dtx.CodeDetail_CheckExist(cmcode, cdcode).ToList();
        if (ltResult.Count > 0)
            return true;
        else
            return false;
    }

    bool IsExistDeleteCodeDetail(string cmcode, string cdcode)
    {
        DBDataContext dtx = LINQUtil.GetDBReadOnly();
        List<CodeDetail_CheckDeleteResult> listResult = dtx.CodeDetail_CheckDelete(cmcode, cdcode).ToList();
        if (listResult.Count > 0)
            return true;
        else
            return false;
    }

    protected void SaveData()
    {
        try
        {
            if (cboCMCode.Text == "" && txtCDCode.Text == "")
            {
                cboCMCode.Focus();
                lblCMCode.Text = "Không được rỗng";
                lblCDCode.Text = "Không được rỗng";
                return;
            }
            if (cboCMCode.Text == "")
            {
                cboCMCode.Focus();
                lblCMCode.Text = "Không được rỗng";
                return;
            }
            if (txtCDCode.Text == "")
            {
                txtCDCode.Focus();
                lblCDCode.Text = "Không được rỗng";
                return;
            }
            if (FormState == 0)
            {
                if (IsExistCodeDetail(cboCMCode.Text, txtCDCode.Text))
                {
                    //lblResult.Text = "Đã tồn tại";
                    JavascriptUtil.LoadMessage(u, false, "Đã tồn tại.");
                    return;
                }
            }

            if (txtNumberValue.Text == "")
            {
                txtNumberValue.Text = "0";
            }
            if (txtOrdinal.Text == "")
            {
                txtOrdinal.Text = "0";
            }
            //bỏ những ký tự đặc biệt, chống SQL Injection
            txtCDName.Text = Utils.KillChars(txtCDName.Text);
            txtStandardName.Text = Utils.KillChars(txtStandardName.Text);
            txtNumberValue.Text = Utils.KillChars(txtNumberValue.Text);
            txtOrdinal.Text = Utils.KillChars(txtOrdinal.Text);
            txtRemark.Text = Utils.KillChars(txtRemark.Text);


            //DB.ClearParameter();
            ////Add param cho store
            //DbParameter paramCMCode = DB.Parameter;
            //paramCMCode.ParameterName = "CMCode";
            //paramCMCode.DbType = DbType.String;
            //paramCMCode.Value = cboCMCode.Text;
            //DB.AddParameter(paramCMCode);

            //DbParameter paramCDCode = DB.Parameter;
            //paramCDCode.ParameterName = "CDCode";
            //paramCDCode.DbType = DbType.String;
            //paramCDCode.Value = txtCDCode.Text;
            //DB.AddParameter(paramCDCode);

            //DbParameter paramCDName = DB.Parameter;
            //paramCDName.ParameterName = "CDName";
            //paramCDName.DbType = DbType.String;
            //paramCDName.Value = txtCDName.Text;
            //DB.AddParameter(paramCDName);

            //DbParameter paramStandardName = DB.Parameter;
            //paramStandardName.ParameterName = "StandardName";
            //paramStandardName.DbType = DbType.String;
            //paramStandardName.Value = txtStandardName.Text;
            //DB.AddParameter(paramStandardName);

            //DbParameter paramNumberValue = DB.Parameter;
            //paramNumberValue.ParameterName = "NumberValue";
            //paramNumberValue.DbType = DbType.Double;
            //paramNumberValue.Value = Double.Parse(txtNumberValue.Text.ToString());
            //DB.AddParameter(paramNumberValue);

            //DbParameter paramOrdinal = DB.Parameter;
            //paramOrdinal.ParameterName = "Ordinal";
            //paramOrdinal.DbType = DbType.Int32;
            //paramOrdinal.Value = Int32.Parse(txtOrdinal.Text.ToString());
            //DB.AddParameter(paramOrdinal);

            //DbParameter paramRemark = DB.Parameter;
            //paramRemark.ParameterName = "Remark";
            //paramRemark.DbType = DbType.String;
            //paramRemark.Value = txtRemark.Text;
            //DB.AddParameter(paramRemark);

            //DbParameter paramStatus = DB.Parameter;
            //paramStatus.ParameterName = "Status";
            //paramStatus.DbType = DbType.String;
            //paramStatus.Value = "A";
            //DB.AddParameter(paramStatus);

            //DbParameter paramByUser = DB.Parameter;
            //paramByUser.ParameterName = "ByUser";
            //paramByUser.DbType = DbType.String;
            //paramByUser.Value = Session["UserName"].ToString(); //User đang thao tác
            //DB.AddParameter(paramByUser);

            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
            if (FormState == 0)
            {
                if (IsExistDeleteCodeDetail(cboCMCode.Text, txtCDCode.Text))
                {
                    dtx.CodeDetail_Update(cboCMCode.Text, txtCDCode.Text, txtCDName.Text, txtStandardName.Text, Double.Parse(txtNumberValue.Text.ToString()), Int32.Parse(txtOrdinal.Text.ToString()), txtRemark.Text, ObjectStatus.Active, Session["UserName"].ToString());
                }
                else
                {
                    //dt = DB.ExecuteDataTable("CodeDetail_Create", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                    dtx.CodeDetail_Create(cboCMCode.Text, txtCDCode.Text, txtCDName.Text, txtStandardName.Text, Double.Parse(txtNumberValue.Text.ToString()), Int32.Parse(txtOrdinal.Text.ToString()), txtRemark.Text, ObjectStatus.Active, Session["UserName"].ToString());
                }

                JavascriptUtil.LoadMessage(u, true, "Thêm mới thành công!");
            }
            else if (FormState == 1)
            {
                dtx.CodeDetail_Update(cboCMCode.Text, txtCDCode.Text, txtCDName.Text, txtStandardName.Text, Double.Parse(txtNumberValue.Text.ToString()), Int32.Parse(txtOrdinal.Text.ToString()), txtRemark.Text, ObjectStatus.Active, Session["UserName"].ToString());
                JavascriptUtil.LoadMessage(u, true, "Cập nhật thành công!");
                FormState = 0;
            }
        }
        catch (Exception ex)
        {
            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;
        }
    }

    protected void DeleteData()
    {
        //DB.ClearParameter();

        ////Add param cho store
        //DbParameter paramCMCode = DB.Parameter;
        //paramCMCode.ParameterName = "CMCode";
        //paramCMCode.DbType = DbType.String;
        //paramCMCode.Value = cboCMCode.SelectedValue;
        //DB.AddParameter(paramCMCode);

        //DbParameter paramCDCode = DB.Parameter;
        //paramCDCode.ParameterName = "CDCode";
        //paramCDCode.DbType = DbType.String;
        //paramCDCode.Value = txtCDCode.Text;
        //DB.AddParameter(paramCDCode);

        //DbParameter paramByUser = DB.Parameter;
        //paramByUser.ParameterName = "ByUser";
        //paramByUser.DbType = DbType.String;
        //paramByUser.Value = Session["UserName"].ToString(); //User đang thao tác
        //DB.AddParameter(paramByUser);

        try
        {
            //dt = DB.ExecuteDataTable("CodeDetail_Delete", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
            dtx.CodeDetail_Delete(cboCMCode.SelectedValue, txtCDCode.Text, Session["UserName"].ToString());
            JavascriptUtil.LoadMessage(u, true, "Xóa thành công!");
        }
        catch (Exception ex)
        {
            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;
        }
    }

    protected Boolean CheckAllBeforeSave()
    {
        Boolean flag = true;
        if (txtCDName.Text == "")
        {
            //lblResult.Text = "[Tên danh mục] không được rỗng";
            JavascriptUtil.LoadMessage(u, true, "[Tên danh mục] không được rỗng.");
            flag = false;
        }
        return flag;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        SaveData();
        Session["CodeDetail"] = 1;
        btnNew.Focus();
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        ClearForm();
        SetEnable();
        btnDelete.Focus();
        //lblResult.Text = "";
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DeleteData();
        ClearForm();
        SetEnable();
        btnGotoList.Focus();
    }

    protected void btnGotoList_Click(object sender, EventArgs e)
    {
        FormState = 0;
        Response.Redirect("~/CodeDetailList");
    }
    protected void txtCDCode_TextChanged(object sender, EventArgs e)
    {
        txtCDName.Focus();
    }
    protected void cboCMCode_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtCDCode.Focus();
    }
    protected void txtCDName_TextChanged(object sender, EventArgs e)
    {
        txtStandardName.Focus();
    }
    protected void txtStandardName_TextChanged(object sender, EventArgs e)
    {
        txtNumberValue.Focus();

    }
    protected void txtNumberValue_TextChanged(object sender, EventArgs e)
    {
        dtpDateTimeValue.Focus();
    }
    protected void dtpDateTimeValue_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
    {
        txtOrdinal.Focus();
    }
    protected void txtOrdinal_TextChanged(object sender, EventArgs e)
    {
        txtRemark.Focus();
    }
    protected void cboStatus_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        btnSave.Focus();
    }
    protected void txtRemark_TextChanged(object sender, EventArgs e)
    {
        cboStatus.Focus();
    }
}
